// 导入依赖的模块
yepjs.require("jquery");
yepjs.require("YBA.Common");
yepjs.require("YBA.Plugin.plugins");
yepjs.require("YBA.Plugin.wdatePicker");
yepjs.require("YBA.Data.Admin");

// 后台管理 - 服务器列表管理
yepjs.define("list", {

    NS: "YBA.Logic.Admin",

    field: function() {

        var Biz = {
            // 初始化事件
            init: function() {

                Biz.fn.getServerList(function (json) {

                    // 设置初始列表项目的数量，创建分页控件需要使用该数量
                    Biz.vars.totalNum = json.page.totalRecord;

                    for (var i in Biz.event) {
                        Biz.event[i]();
                    }
                });
            },
            //  公共变量
            vars: {
                // 模板列表
                tpl: (function(){
                    var tpl = {};
                    $("script[type='text/ysmart']").each(function(){
                        var t = $(this);
                        tpl[t.attr("data-name")] = t.html();
                    });
                    return tpl;
                })(),
                // 报表搜索字段
                searchVar: {
                    host: "",          // 主机地址  string  可选
                    name: "",      // 存储云编号  string  可选
                    internalHost: "",          // 内部主机地址  string  可选
                    startPos: 1,          // 当前页  int  必填
                    pageSize: 18          // 页面大小  int  必填
                },
                // 列表项目的总数量
                totalNum: 0,
                // 分页控件引用
                pageCtrl: null
            },
            // 页面元素
            el: {
                body: $("body"),
                jhost: $("#j-host"),
                jinternalHost: $("#j-internalHost"),
                jstorageCloudId: $("#j-storageCloudId"),
                jpage: $("#j-page"),
                jlist: $("#j-list"),
                jaddServer: $("#j-addServer"),
                jdeleteServer:$("#j-deleteServer"),
                jallObj:$(".j-checkAll"),
                jtotalNum: $("#j-totalNum")
            },
            // 功能函数集合
            fn: {
                // 读取终端列表
            	getServerList: function (callback) {
                    YBA.Data.Admin.getServerList(Biz.vars.searchVar, function (json) {
                        if(json.code == 200) {
                            Biz.el.jlist.html(YBA.Common.ysmart(Biz.vars.tpl.list, json.list));
                            Biz.el.jtotalNum.html(json.page.totalRecord);

                            Biz.vars.pageCtrl && Biz.vars.pageCtrl.setTotalNum(json.page.totalRecord);

                            callback && callback(json);
                        }else{
                            YBA.Plugin.msgtip({type: "i", msg: json.desc})
                        }
                    });
                },
                // 表单验证
                formCheck: function(form,name) {
                	// 显示错误信息
                    var showError = function(obj, msg) {
                        var msgDom = obj.siblings('.message');
                        var msgTxt = msgDom.children('i')
                        msgDom.addClass("msg-error").removeClass('msg-tip');
                        msgTxt.html(msg);
                        msgDom.show();
                    };

                    // 隐藏错误信息
                    var hideError = function(obj, msg) {
                        var msgDom = obj.siblings('.message');
                        var msgTxt = msgDom.children('i')
                        msgDom.hide();
                        msgDom.addClass("msg-tip").removeClass('msg-error');
                        msgTxt.html(msg);
                    };

                    // 数据验证对象
                    var dataCheck = {
                        host:{
                            obj: form.find("[name='host']"),
                            fn: function() {
                                var val = this.obj.val();
                                if (YBA.Common.check.isNull(val)) {
                                    showError(this.obj,"请输入主机地址");
                                    return false;
                                } else if(!YBA.Common.check.isIP(val)){
                                	showError(this.obj,"输入不合法");
                                    return false;
                                } else if(YBA.Common.check.isHowLong(val,50)){
                                	showError(this.obj,"主机地址过长");
                                    return false;
                                } else {
                                    hideError(this.obj,"请输入主机地址");
                                    return true;
                                }
                            }
                        },
                        port: {
                            obj: form.find("[name='port']"),
                            fn: function() {
                                var val = this.obj.val();
                                if (YBA.Common.check.isNull(val)) {
                                    showError(this.obj,"请输入端口号");
                                    return false;
                                } else if(!YBA.Common.check.isNum(val,{"min":0,"max":65535,"decimals":0})){
                                	showError(this.obj,"端口号范围0~65535");
                                    return false;
                                } else if(!YBA.Common.check.isPort(val)){
                                	showError(this.obj,"输入不合法");
                                    return false;
                                } else if(YBA.Common.check.isHowLong(val,11)){
                                	showError(this.obj,"端口号过长");
                                    return false;
                                } else {
                                    hideError(this.obj,"请输入端口号");
                                    return true;
                                }
                            }
                        },
                        internalHost:{
                            obj: form.find("[name='internalHost']"),
                            fn: function() {
                                var val = this.obj.val();
                                if (YBA.Common.check.isNull(val)) {
                                    showError(this.obj,"请输入主机地址");
                                    return false;
                                } else if(!YBA.Common.check.isIP(val)){
                                	showError(this.obj,"输入不合法");
                                    return false;
                                } else if(YBA.Common.check.isHowLong(val,50)){
                                	showError(this.obj,"主机地址过长");
                                    return false;
                                } else {
                                    hideError(this.obj,"请输入主机地址");
                                    return true;
                                }
                            }
                        },
                        internalPort: {
                            obj: form.find("[name='internalPort']"),
                            fn: function() {
                                var val = this.obj.val();
                                if (YBA.Common.check.isNull(val)) {
                                    showError(this.obj,"请输入端口号");
                                    return false;
                                } else if(!YBA.Common.check.isNum(val,{"min":0,"max":65535,"decimals":0})){
                                	showError(this.obj,"端口号范围0~65535");
                                    return false;
                                } else if(!YBA.Common.check.isPort(val)){
                                	showError(this.obj,"输入不合法");
                                    return false;
                                } else if(YBA.Common.check.isHowLong(val,11)){
                                	showError(this.obj,"端口号过长");
                                    return false;
                                } else {
                                    hideError(this.obj,"请输入端口号");
                                    return true;
                                }
                            }
                        },
                        storageCloudId: {
                            obj: form.find("[name='storageCloudId']"),
                            fn: function() {
                                var val = this.obj.val();
                                if (YBA.Common.check.isNull(val)) {
                                    showError(this.obj,"请输入存储云编号");
                                    return false;
                                } else if(YBA.Common.check.isHowLong(val,50)){
                                	showError(this.obj,"存储云编号过长");
                                    return false;
                                } else {
                                    hideError(this.obj,"请输入存储云编号");
                                    return true;
                                }
                            }
                        }
                    };

                    if (name && dataCheck[name]) {
                        return dataCheck[name].fn();
                    } else {
                        var errLen = 0;
                        for (var i in dataCheck) {
                            if (!dataCheck[i].fn()) {
                                errLen++;
                            }
                        }
                        if (errLen > 0) {
                            return false;
                        }
                        return true;
                    }
                },
                //获取云存储列表
                getCloudList:function(dom,data){
                	if(!data){
                		data = {
                			"storageCloudId" : ""
                		}
                	}
                    YBA.Data.Admin.getStorageCloudList({"startPos": 1,"pageSize": 0 }, function(json){
                        if(json.code == 200) {
                            var str = "";
                            for(var i = 0; i < json.list.length ; i++){
                            	if(data.storageCloudId == json.list[i].id){
                            		str+="<option value='"+json.list[i].id+"' selected='selected'>"+json.list[i].name+"</option>";
                            	}else{
                            		str+="<option value='"+json.list[i].id+"'>"+json.list[i].name+"</option>";
                            	}
                            }
                            dom.html(str);
                        }
                    });
                },
                // 服务器新增或修改弹窗
                serverForm: function(data){

                    var popform = new YBA.Plugin.popform({
                        title: (!(data))?"新增服务器":"修改服务器",
                        className: "ui-dialog-server",
                        content: YBA.Common.ysmart(Biz.vars.tpl.serverTpl, data || {} ),
                        width: 564,
                        destroy: true,
                        onHide: function () {
                            // 隐藏弹窗时要执行的回调函数
                        },
                        onShow: function () {
                            // 显示弹窗时要执行的回调函数
                            var op = $(".form-group");
                            var form = $(".ui-dialog-form");
                            op.each(function() {
                                var t = $(this),
                                    input = t.find(".required"),
                                    name = input.attr("name"),
                                    holder = input.siblings(".message");
                                input.blur(function() {
                                    Biz.fn.formCheck(form,name);
                                }).focus(function() {
                                    holder.show();
                                });;
                            });
                            Biz.fn.getCloudList($("#j-cloudId"),data);
                        },
                        btns: [{
                            value: "确定",
                            className: "blue btn g-mr10",
                            fn: function () {
                                var form = $(".ui-dialog-form");
                                if (!Biz.fn.formCheck(form)) {
                                    return false;
                                }else{
                                    var form = popform.self.find("form");
                                    var data = form.serialize();
                                    var dataId = $("#j-dataId").val();
                                    var callbackFn = function(json){
                                        if(json.code == 200) {
                                            YBA.Plugin.msgtip({type: "o", msg: json.desc});
                                            popform.hide();
                                            Biz.fn.getServerList();
                                        }else{
                                            YBA.Plugin.msgtip({type: "i", msg: json.desc});
                                        }
                                    }
                                    if(!dataId){
                                        YBA.Data.Admin.addServer(data, callbackFn);
                                    }else{
                                        YBA.Data.Admin.updateServer(data, callbackFn);
                                    }
                                }
                            }
                        }, {
                            value: "取消",
                            className: "red btn g-ml10",
                            fn: function () {
                                popform.hide();
                            }
                        }]
                    }).show();

                    return false;
                },
                // 获取服务器详情
                getServerDetail: function(id, callback){
                    YBA.Data.Admin.getServerDetail({id: id}, function(json){
                        if(json.code == 200) {
                            callback && callback(json.obj);
                        }else{
                            YBA.Plugin.msgtip({type: "i", msg: json.desc})
                        }
                    })
                },
                //删除服务器
                deleteServer:function(data){
                    var confirm = YBA.Plugin.confirm({
                        msg: "您确定要删除这些服务器吗？",
                        btnTxt1: "确定",
                        yes: function () {
                            confirm.hide();
                            YBA.Data.Admin.deleteServer(data, function (json) {
                                if(json.code == 200){
                                    YBA.Plugin.msgtip({type: "o", msg: "操作成功"});
                                    Biz.vars.searchVar.startPos = 1;
                                    Biz.vars.pageCtrl.setPageIndex(1);
                                    Biz.el.jallObj.prop("checked", false);
                                    Biz.fn.getServerList();
                                }else{
                                    YBA.Plugin.msgtip({type: "i", msg: "操作失败"});
                                }
                            })
                        }
                    })
                }
            },
            // 初始化时执行的所有事件
            event: {
                // 搜索
                search: function () {
                    // 点击“查询”时，设置搜索条件
                    Biz.el.body.delegate(".j-search", "click", function () {
                        Biz.vars.searchVar.host = Biz.el.jhost.val();
                        Biz.vars.searchVar.internalHost = Biz.el.jinternalHost.val();
                        Biz.vars.searchVar.name = Biz.el.jstorageCloudId.val();
                        Biz.vars.searchVar.startPos = 1;

                        Biz.vars.pageCtrl.setPageIndex(1);

                        Biz.fn.getServerList();
                    });

                    // 点击“重置”时，重置搜索条件
                    Biz.el.body.delegate(".j-reset", "click", function () {

                        Biz.el.jhost.val("");
                        Biz.el.jinternalHost.val("");
                        Biz.el.jstorageCloudId.val("");

                        Biz.vars.searchVar.host = "";
                        Biz.vars.searchVar.internalHost = "";
                        Biz.vars.searchVar.name = "";
                        Biz.vars.searchVar.startPos = 1;

                        Biz.vars.pageCtrl.setPageIndex(1);

                        Biz.fn.getServerList();
                    });
                },
                // 分页
                pageNav: function () {
                    // 创建分页控件
                    Biz.vars.pageCtrl = new YBA.Plugin.pageNav({
                        // 放置分页控件的容器
                        pageCon: Biz.el.jpage,
                        // 每页数量
                        pageSize: Biz.vars.searchVar.pageSize,
                        // 总数量
                        totalNum: Biz.vars.totalNum,
                        // 回调函数
                        callback: function (pageIndex) {
                            // 设置页次
                            Biz.vars.searchVar.startPos = pageIndex;
                            // 执行搜索
                            Biz.fn.getServerList();
                        }
                    });
                },
                //复选框全选
                checkAll:function(){
                    YBA.Plugin.checkAll({
                        allObj:Biz.el.jallObj,
                        eachObj:$(".j-checkEach"),
                        list:$("#j-list")
                    })
                },
                //新增服务器
                addServer: function(){
                    Biz.el.jaddServer.bind("click", function(){
                        Biz.fn.serverForm();
                    });
                },
                //管理服务器
                serverAdmin:function(){
                    Biz.el.jlist.delegate(".j-admin", "click", function(){
                        var t = $(this), tr = t.closest("tr"), id = tr.attr("data-id");
                        Biz.fn.getServerDetail(id, function(data){
                            Biz.fn.serverForm(data);
                        });
                    });
                },
                // 批量删除
                deleteServer: function(){
                    Biz.el.jdeleteServer.bind("click", function(){
                        var idStr = "";
                        var data = {};
                        $(".j-checkEach").each(function(){
                            var t = $(this);
                            if(t.is(':checked')){
                                var tr = t.closest("tr"), id = tr.attr("data-id");
                                if(idStr == ""){
                                    idStr = id
                                }else{
                                    idStr = idStr+","+id;
                                }
                            }
                        });
                        if(idStr == ""){
                            YBA.Plugin.msgtip({type: "i", msg: "没有选中项！"})
                            return false;
                        }
                        data = {
                            "ids":idStr
                        }
                        Biz.fn.deleteServer(data);
                    });
                },
            }
        };

        Biz.init();

        return Biz;
    }
});
